package com.sg.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class SQLSessionFactory {

    private static SqlSessionFactory sqlSessionFactory;
    
    private static final Lock lock = new ReentrantLock();
    
    private static SQLSessionFactory instance;
    
    private SQLSessionFactory() {
        String resource = "com/sg/config/mybatis-config.xml";
        InputStream inputStream;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    public static SQLSessionFactory getInstance() {
        lock.lock();
        try {
            if(instance == null) {
                instance = new SQLSessionFactory();
            }
        }finally {
            lock.unlock();
        }
        return instance;
    }
    
    public SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
    
}
